package com.example.agriapp.view.activity;

import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.agriapp.model.ProductContract;
import com.example.agriapp.R;
import com.example.agriapp.data.AgriDatabaseHelper;
import com.example.agriapp.util.PathUtil;

import java.io.FileNotFoundException;

public class PublishActivity extends AppCompatActivity {
    private static final int PICK_IMAGE_REQUEST = 1;

    private RadioGroup rgPublishType;
    private LinearLayout llProductForm;
    private LinearLayout llPurchaseForm;
    private EditText etProductName, etProductDescription, etProductPrice;
    private EditText etProductCategory, etProductStock;
    private ImageView ivProductImage,ivImage;
    private LinearLayout btnAddMedia,btn_media;
    private ProgressBar progressBar;
    private Button btnPublish;
    private Uri imageUri;
    private AgriDatabaseHelper agriDatabaseHelper;
    private String selectedImagePath;
    private EditText et_purchase_category, et_purchase_description, et_purchase_expected_price, et_purchase_title, et_purchase_quantity,et_image_url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish);
        agriDatabaseHelper = new AgriDatabaseHelper(this);
        initViews();
        setupListeners();
    }

    private void initViews() {
        rgPublishType = findViewById(R.id.rg_publish_type);
        llProductForm = findViewById(R.id.ll_product_form);
        llPurchaseForm = findViewById(R.id.ll_purchase_form);
        etProductName = findViewById(R.id.et_product_name);
        etProductDescription = findViewById(R.id.et_product_description);
        etProductPrice = findViewById(R.id.et_product_price);
        etProductCategory = findViewById(R.id.et_product_category);
        etProductStock = findViewById(R.id.et_product_stock);
        ivProductImage = findViewById(R.id.et_product_image_url);
        et_purchase_quantity = findViewById(R.id.et_purchase_quantity);
        ivImage = findViewById(R.id.image_url);
        btnAddMedia = findViewById(R.id.btn_add_media);
        btn_media = findViewById(R.id.btn_media);
        progressBar = findViewById(R.id.progress_bar);
        progressBar = findViewById(R.id.progress_bar);
        et_purchase_category = findViewById(R.id.et_purchase_category);
        et_purchase_description = findViewById(R.id.et_purchase_description);
        et_purchase_expected_price = findViewById(R.id.et_purchase_expected_price);
        et_purchase_title = findViewById(R.id.et_purchase_title);
        et_image_url = findViewById(R.id.et_image_url);
        progressBar = findViewById(R.id.progress_bar);
        progressBar = findViewById(R.id.progress_bar);
        progressBar = findViewById(R.id.progress_bar);
        btnPublish = findViewById(R.id.btn_publish);
    }

    private void setupListeners() {
        // 发布类型切换
        rgPublishType.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.rb_publish_product) {
                llProductForm.setVisibility(View.VISIBLE);
                llPurchaseForm.setVisibility(View.GONE);
            } else {
                llProductForm.setVisibility(View.GONE);
                llPurchaseForm.setVisibility(View.VISIBLE);
            }
        });

        // 添加图片按钮点击事件
        btnAddMedia.setOnClickListener(v -> openImageChooser());
        btn_media.setOnClickListener(v -> openImageChooser());

        // 发布按钮点击事件
        btnPublish.setOnClickListener(v -> {
            if (rgPublishType.getCheckedRadioButtonId() == R.id.rb_publish_product) {
                publishProduct();
            } else {
                publishPurchase();
            }
        });
    }

    private void openImageChooser() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PICK_IMAGE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
            Uri imageUri = data.getData();
            Bitmap bitmap = null;
            try {
                bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                if (rgPublishType.getCheckedRadioButtonId()==R.id.rb_publish_product) {
                    ivProductImage.setImageBitmap(bitmap);
                    ivProductImage.setVisibility(View.VISIBLE);
                    btnAddMedia.setVisibility(View.GONE);
                    selectedImagePath = PathUtil.getRealPathFromUri(this, imageUri);
                }else {
                    ivImage.setImageBitmap(bitmap);
                    ivImage.setVisibility(View.VISIBLE);
                    btn_media.setVisibility(View.GONE);
                    selectedImagePath = PathUtil.getRealPathFromUri(this, imageUri);
                }

            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }

        }
    }

    private void publishProduct() {
        String name = etProductName.getText().toString().trim();
        String description = etProductDescription.getText().toString().trim();
        double price = Double.parseDouble(etProductPrice.getText().toString().trim());
        String category = etProductCategory.getText().toString().trim();
        int stock = Integer.parseInt(etProductStock.getText().toString().trim());

        if (name.isEmpty() || description.isEmpty() ||
                category.isEmpty() || selectedImagePath.isEmpty()) {
            Toast.makeText(this, "请填写所有产品信息并选择图片", Toast.LENGTH_SHORT).show();
            return;
        }

        //showLoading(true);
        // TODO: 实现产品发布逻辑，包含图片URI上传
        insertTestProduct(name, price, stock, category);
    }

    private void insertTestProduct(
            String title, double price, int quantity,
            String category) {
        SQLiteDatabase writableDatabase = agriDatabaseHelper.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(ProductContract.ProductEntry.COLUMN_TITLE, title);
        values.put(ProductContract.ProductEntry.COLUMN_PRICE, price);
        values.put(ProductContract.ProductEntry.COLUMN_QUANTITY, quantity);
        values.put(ProductContract.ProductEntry.COLUMN_CATEGORY, category);

        values.put(ProductContract.ProductEntry.COLUMN_IMAGE, selectedImagePath);

        writableDatabase.insert(ProductContract.ProductEntry.TABLE_NAME,null,values);
        finish();

    }

    private void publishPurchase() {
        // 采购发布逻辑
        //showLoading(true);
        String title = et_purchase_title.getText().toString().trim();
        String category = et_purchase_category.getText().toString().trim();
        String description = et_purchase_description.getText().toString().trim();
        String price = et_purchase_expected_price.getText().toString().trim();
        String quantity = et_purchase_quantity.getText().toString().trim();

        if (title.isEmpty() || description.isEmpty() ||price.isEmpty() ||quantity.isEmpty()||
                category.isEmpty() || selectedImagePath.isEmpty()) {
            Toast.makeText(this, "请填写所有产品信息并选择图片", Toast.LENGTH_SHORT).show();
            return;
        }

        agriDatabaseHelper.addPurchase(1,title,description,category,Integer.parseInt(quantity),Double.parseDouble(price),selectedImagePath);
        finish();
        // TODO: 实现采购发布逻辑
    }

    private void showLoading(boolean show) {
        progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
        btnPublish.setEnabled(!show);
    }
}